package com.avalon.stop;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.management.JMX;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import com.avalon.BootEnvironment;
import com.avalon.SubstitutionProperties;
import com.avalon.jmx.AvalonInstanceMXBean;

public final class Stop {

	private static final Logger logger = Logger.getLogger(Stop.class.getName());

	private Stop() {
	}

	public static void main(String args[]) throws Exception {
		if (args.length > 1) {
			logger.log(Level.SEVERE, "Invalid number of arguments");
			throw new IllegalArgumentException("Invalid number of arguments");
		}
		SubstitutionProperties properties = null;
		if (args.length == 0) {
			properties = BootEnvironment.loadProperties(null);
		} else {
			properties = BootEnvironment.loadProperties(args[0]);
		}
		String port = properties.getProperty("JMX_PORT", "62974");
		JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://127.0.0.1:" + port + "/jmxrmi");
		JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
		javax.management.MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
		//com.avalon:name=AvalonEngine,type=AvalonInstance
		ObjectName name = new ObjectName("com.avalon:name=AvalonEngine,type=AvalonInstance");
		AvalonInstanceMXBean proxy = (AvalonInstanceMXBean) JMX.newMXBeanProxy(mbsc, name, AvalonInstanceMXBean.class);
		proxy.stopEngine();
	}

}
